const { Existing, AuthFailed, NotFound } = require('../core/http-exception')
const { redis, generateToken, isModelOne, Mailer, createAuthCode } = require('../common')
const { Like, User } = require('../models')
const { authCode } = require('../config')
const { Op } = require('sequelize')
const multer = require('koa-multer')
const moment = require('moment')
const fs = require('fs')
const path = require('path')

class DefaultController {
  static async like(data, auth) {
    await isModelOne(data.get('type'), data.get('target_id'))

    const flag = await Like.findOne({
      where: {
        user_id: auth.id,
        type: data.get('type'),
        target_id: data.get('target_id')
      }
    })
    if (flag) {
      throw new AuthFailed('你已经点赞')
    }

    await Like.create({
      user_id: auth.id,
      type: data.get('type'),
      target_id: data.get('target_id')
    })

    const result = await Like.findAndCountAll({
      where: {
        type: data.get('type'),
        target_id: data.get('target_id')
      }
    })

    return result.count
  }

  static async image(ctx, next) {
    //文件上传
    //配置
    var storage = multer.diskStorage({
      //文件保存路径
      destination: async function(req, file, cb) {
        const date = moment(Date.now()).format('YYYY-MM-DD')
        const p = path.join(__dirname + '../../static/images') + '/' + date
        fs.exists(p, function(flag) {
          if (!flag) {
            fs.mkdirSync(p)
          }

          cb(null, 'server/static/images/' + date)
        })
      },
      //修改文件名称
      filename: function(req, file, cb) {
        var fileFormat = file.originalname.split('.') //以点分割成数组，数组的最后一项就是后缀名
        cb(null, Date.now() + '.' + fileFormat[fileFormat.length - 1])
      }
    })
    //加载配置
    var upload = multer({
      storage: storage,
      limits: {
        fileSize: 1024 * 500
      },
      fileFilter(req, file, cb) {
        const t = file.originalname.split('.')
        const ts = ['jpg', 'jpeg', 'png']

        if (ts.includes(t[t.length - 1])) {
          cb(null, true)
        } else {
          cb(new Error())
        }
      }
    })

    let err = await upload
      .single('image')(ctx, next)
      .then(res => res)
      .catch(err => err)

    if (err) {
      throw new ParameterException(
        '图片大小不能超过500kb, 并且类型需为jpg/png/jpeg'
      )
    }

    return ctx.req.file.path.replace('server/static', '')
  }

  // 创建验证码
  static async authcode(data, type, ctx, msg) {
    let filter = {};
    if(ctx.auth){
      filter.id = ctx.auth.id;
    } else {
      filter.email = data.get('email');
    }
    const user = await User.findOne({
      where: filter
    })
    switch(type){
      case authCode.register_user:
        if(user) throw new AuthFailed('用户已经存在');
        break;
      case authCode.update_password:
        if(!user) throw new AuthFailed('用户不存在');
        break;
    }
    const email = user ? user.email : data.get('email');
    const key = email + '-' + type

    await Mailer.delay(key, 60)

    const code = createAuthCode()
    await redis.set('authCode', key, code, 60 * 30)

    const flag = await Mailer.send({
      to: email,
      type: 'authcode',
      title: msg,
      code,
      ctx
    })
    
    return flag;
  }
}

module.exports = DefaultController
